import {rpx2px} from "../../../../utils/tool";

Component({
    properties: {
        cate:{
            type:Object, value:null,
            observer(data){
                if (data && data.children){
                    data.children.unshift({id:-1,title:'全部', children:[]})
                }
                this.setData({
                    index:0,
                    tabsScrollLeft:0,
                    _cate:data
                })

                // 父分类改变，计算子分类的宽度集合
                wx.createSelectorQuery().in(this).selectAll('.mi_tabs_li').boundingClientRect( (rects) => {
                    let left = 0
                    const childLeftArr = rects.map((item,index,arr) => {
                        if (index == 0){
                            left = 0
                        }else{
                            left = left + arr[index-1].width + rpx2px(32)
                        }

                        return left
                    })

                    this.setData({
                        childLeftArr
                    })
                }).exec()
            }
        },
        index:{type:Number,value:0}
    },
    data: {
        tagShow:false,  // 是否显示全部下级分类
        tabsScrollLeft:0,
        childLeftArr:[],    // 滚动条中的每个分类距离滚动框最左边的距离
        _cate:{},
    },
    methods: {
        tagToggle(){
            this.setData({
                tagShow: !this.data.tagShow
            })
        },
        tabChange(e){
            this.cateChange(e)
        },
        tagChange(e){
            this.cateChange(e)
            // 修改tabs滚动条位置
            const {index} = e.currentTarget.dataset
            const {childLeftArr} = this.data
            this.setData({
                tabsScrollLeft: childLeftArr[index],
                tagShow:false,
            })
        },
        /**
         * 选中分类事件
         * @param e
         */
        cateChange(e){
            const {index} = e.currentTarget.dataset
            const {_cate} = this.data
            this.setData({
                index,
            })
            this.triggerEvent("change", {
                index,
                twoCate: _cate.children[index]
            })
        }
    }
});
